package com.ghd.dataviz.utils;

import com.ghd.dataviz.param.KpiDatas;
import com.ghd.dataviz.entity.RealtimeData;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author ：ghd
 * @date ：Created in 2020-03-10 22:54
 * @description：utils
 * @modified By：
 * @version: 1.0$
 */
public class KpiUtil {
    private static final int COLUMN_LEN = 20;
    private static final String COLUMN_PREFIX = "col";

    public static KpiDatas convert(List<RealtimeData> dataList) {
        KpiDatas datas = new KpiDatas();
        Map<String, List<List<String>>> data = new HashMap<>();
        if (CollectionUtils.isEmpty(dataList)) {
            datas.setData(data);
            return datas;
        }
        Map<String, List<RealtimeData>> tmpData =
                dataList.stream().collect(Collectors.groupingBy(RealtimeData::getKpi));
        for (Map.Entry<String, List<RealtimeData>> entry : tmpData.entrySet()) {
            List<List<String>> lists = entry.getValue().stream().map(KpiUtil::getColumns)
                    .collect(Collectors.toList());
            data.put(entry.getKey(), lists);
        }
        datas.setData(data);
        return datas;
    }

    public static List<String> getColumns(RealtimeData data) {
        return IntStream.range(1, COLUMN_LEN).mapToObj(pre -> {
            try {
                return BeanUtils.getProperty(data, COLUMN_PREFIX + pre);
            } catch (Exception e) {
                return "";
            }
        }).collect(Collectors.toList());
    }
}
